// 导入数据库API
const db = require("../../config/db");
// 导入加密/解密文件
const aes2 = require("../../utils/aes2");
// 导入jwt token工具
const JwtUtil = require("../../utils/jwt");
// 正在表达式
const rep_phone = /^1[3-9]\d{9}$/;
const rep_email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
// 默认头像 , 例如： http://localhost:3000/imgs/1.jpg
let { HOST_URL } = require("../../config/host");
let admin_avators = ["/imgs/1.jpg", "/imgs/2.jpg", "/imgs/3.jpg", "/imgs/4.jpg", "/imgs/5.jpg", "/imgs/6.jpg"];
let rd = () => {
    return Math.floor(Math.random() * admin_avators.length);
};

// 封装注册接口
const register = (admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time) => {
    return new Promise((resolve, reject) => {
        let admin_check_sql = `select * from db_admin where admin_acc = "${admin_acc}"`;
        db.query(admin_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: "查询用户异常。",
                });
            } else {
                // result: 数组
                // result.length == 0 该账号还没被注册
                // console.log("4.0", { admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time });
                if (result.length == 0) {
                    let pwd = aes2.aesEncrypt(admin_pwd); //加密
                    let avator = HOST_URL + admin_avators[rd()]; // 用户默认头像
                    let admin_insert_sql = `insert into db_admin(admin_id,admin_acc,admin_pwd,admin_nick_name,admin_create_time,admin_avator) values("${admin_id}","${admin_acc}","${pwd}","${admin_nick_name}","${admin_create_time}","${avator}")`;
                    db.query(admin_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: "用户注册失败。",
                                err,
                            });
                        } else {
                            resolve({
                                code: 200,
                                msg: "用户注册成功。",
                                admin_nick_name,
                            });
                        }
                    });
                } else {
                    resolve({
                        code: 201,
                        msg: "该账号已经存在。",
                    });
                }
            }
        });
    });
};

// 封装用户登录接口
// 设置用户登录的有效时间
// 把用户的admin_id生产临时的随机字符串(token)
// token: 临时身份（令牌）
const login = (admin_acc, admin_pwd) => {
    return new Promise((resolve, reject) => {
        // 查询用户表sql语句
        let admin_check_sql = "";
        // 判断用户输入的是邮箱还是手机
        if (rep_email.test(admin_acc)) {
            admin_check_sql = `select * from db_admin where admin_acc="${admin_acc}"`;
        } else if (rep_phone.test(admin_acc)) {
            admin_check_sql = `select * from db_admin where admin_phone="${admin_acc}"`;
        }
        console.log({ admin_acc, admin_pwd, admin_check_sql });
        // console.log("6.0", admin_acc, admin_pwd);
        db.query(admin_check_sql, (err, rows) => {
            if (err) {
                resolve({
                    code: -1,
                    msg: "账号或密码错误。",
                });
            } else {
                if (rows.length == 1) {
                    // 匹配密码
                    // 参数1：前端提交的密码，参数2：数据库的密码
                    console.log("7.0", aes2.aesDecrypt(admin_pwd, rows[0]["admin_pwd"]));
                    if (aes2.aesDecrypt(admin_pwd, rows[0]["admin_pwd"])) {
                        let [{ admin_id, admin_nick_name, admin_acc, admin_phone, admin_avator }] = rows;
                        // 将用户id传入并生成token
                        let jwt = new JwtUtil(admin_id);
                        // 获取token
                        let token = jwt.generateToken();
                        // 定义用户对象
                        let user = {
                            code: 200,
                            msg: "恭喜您,登录成功。",
                            token,
                            admin_nick_name,
                            admin_acc,
                            admin_avator,
                        };
                        if (admin_phone) {
                            user["admin_phone"] = admin_phone;
                        }
                        // 将 token 等信息反馈给客户端
                        resolve(user);
                    } else {
                        resolve({
                            code: -1,
                            msg: "账号或密码错误1",
                        });
                    }
                } else if (rows.length == 0) {
                    resolve({
                        code: -1,
                        msg: "账号不存在。",
                    });
                } else {
                    resolve({
                        code: 500,
                        msg: "系统异常。",
                    });
                }
            }
        });
    });
};

// 操作数据库的业务
module.exports = {
    // 示例：
    test() {
        return new Promise((resolve, reject) => {});
    },
    // 注册接口(有邮箱验证)
    register2(admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time, email_code) {
        // 需要用邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    // console.log("邮箱验证码查询失败:",err);
                    reject({
                        code: -1,
                        msg: "邮箱验证码查询失败。",
                    });
                } else {
                    // console.log("rows:",rows)
                    // console.log("length:",rows.length)
                    if (rows.length == 1) {
                        // 注册用户账号
                        register(admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time)
                            .then((res) => {
                                resolve(res);
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        resolve({
                            code: -1,
                            msg: "邮箱验证码查询异常,请重新发送验证码。",
                        });
                    }
                }
            });
        });
    },
    // 登录接口(有邮箱验证)
    login2(admin_acc, admin_pwd, email_code) {
        // 需要邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    // console.log("邮箱验证码查询失败:",err);
                    reject({
                        code: -1,
                        msg: "邮箱验证码查询失败。",
                    });
                } else {
                    if (rows.length == 1) {
                        // 用户账号登录
                        login(admin_acc, admin_pwd)
                            .then((res) => {
                                resolve(res);
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        resolve({
                            code: -1,
                            msg: "邮箱验证码查询异常,请重新发送验证码。",
                        });
                    }
                }
            });
        });
    },
    // 注册接口
    register(admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time) {
        // To do ....
        return register(admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time);
    },
    // 登录接口
    login(admin_acc, admin_pwd) {
        // To do ....
        return login(admin_acc, admin_pwd);
    },
    // 修改用户头像（上传图片）
    modify_avator(admin_id, admin_avator) {
        // console.log({admin_id, admin_avator});
        return new Promise((resolve, reject) => {
            let usr_check_sql = `select * from db_admin where admin_id = "${admin_id}"`;
            db.query(usr_check_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "查询用户失败",
                        err,
                    });
                } else {
                    if (rows.length == 1) {
                        let admin_modify_sql = `update db_admin set admin_avator= "${admin_avator}" where admin_id= "${admin_id}"`;
                        db.query(admin_modify_sql, (error, result) => {
                            // console.log('9.0',{admin_id, admin_avator,error});
                            if (error) {
                                reject({
                                    code: -1,
                                    msg: "修改用户头像失败。",
                                    error,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改用户头像成功。",
                                    admin_avator,
                                });
                            }
                        });
                    }
                }
            });
        });
    },
    // 获取用户头像和昵称
    get_avator_nickname(admin_id) {
        return new Promise((resolve, reject) => {
            let sql = `select admin_avator,admin_nick_name from db_admin where admin_id = "${admin_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "获取头像昵称失败。",
                    });
                } else {
                    reject({
                        code: 200,
                        msg: "获取头像昵称成功。",
                        data: rows,
                    });
                }
            });
        });
    },
    // 修改用户资料
    modify(admin_id, admin_age, admin_addr, admin_phone, admin_sex, admin_nick_name) {
        return new Promise((resolve, reject) => {
            var modify_info_sql = `update db_admin set admin_addr= "${admin_addr}", admin_age= "${admin_age}", admin_phone= "${admin_phone}",admin_sex= "${admin_sex}",admin_nick_name= "${admin_nick_name}" where  admin_id= "${admin_id}"`;
            db.query(modify_info_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "修改用户资料失败。",
                        err,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "修改用户资料成功。",
                    });
                }
            });
        });
    },
    // 删除账号
    remove(admin_id, admin_acc) {
        console.log({ admin_id, admin_acc });
        return new Promise((resolve, reject) => {
            let admin_check_sql = `select admin_acc from  db_admin where admin_id = "${admin_id}" and admin_acc="${admin_acc}"`;
            db.query(admin_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        error,
                    });
                } else {
                    console.log(result);
                    if (result.length == 1) {
                        let admin_remove_sql = `delete from  db_admin where admin_id = "${admin_id}" and admin_acc="${admin_acc}"`;
                        db.query(admin_remove_sql, (err, rows) => {
                            if (err) {
                                reject({
                                    code: -1,
                                    msg: "删除用户失败1。",
                                    err,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "删除用户成功。",
                                });
                            }
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "删除用户失败2。",
                            error,
                        });
                    }
                }
            });
        });
    },
    // 删除账号
    remove(user_id, user_acc) {
        console.log({ user_id, user_acc });
        return new Promise((resolve, reject) => {
            let user_check_sql = `select user_acc from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
            db.query(user_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        error,
                    });
                } else {
                    console.log(result);
                    if (result.length == 1) {
                        let user_remove_sql = `delete from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
                        db.query(user_remove_sql, (err, rows) => {
                            if (err) {
                                reject({
                                    code: -1,
                                    msg: "删除用户失败1。",
                                    err,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "删除用户成功。",
                                });
                            }
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "删除用户失败2。",
                            error,
                        });
                    }
                }
            });
        });
    },
    // 查询账号详情
    detail(admin_id, admin_acc) {
        return new Promise((resolve, reject) => {
            let admin_check_sql = `select admin_acc,admin_age,admin_sex,admin_avator,admin_create_time from  db_admin where admin_id = "${admin_id}" and admin_acc="${admin_acc}"`;
            db.query(admin_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        err,
                    });
                } else {
                    if (result.length == 1) {
                        resolve({
                            code: 200,
                            msg: "查询用户详情成功。",
                            data: result[0],
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "查询用户详情失败。",
                            err,
                        });
                    }
                }
            });
        });
    },
    // 获取用户列表(分页)
    list(page_num, page_size) {
        return new Promise((resolve, reject) => {
            let page_num2 = (page_num - 1) * page_size;
            let page_size2 = page_size;
            // console.log({page_num2, page_size2})
            // let sql = "select * from db_user limit " + page_num2 + "," + page_size2 + ""; // 分页数据
            let sql = "select user_acc,user_nick_name,user_avator,user_create_time,user_id from db_user"; // 查询全部
            db.query(sql, function (err, rows) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: "查询用户失败。",
                        err,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "获取分页列表成功。",
                        result: rows,
                        page: {
                            page_num: page_num,
                            page_size: page_size,
                        },
                    });
                }
            });
        });
    },
    // 统计用户的总数量
    total() {
        return new Promise((resolve, reject) => {
            // 编写统计用户人数方法
            db.query("select count(*) as total from db_user", function (error, among) {
                if (error) {
                    reject({
                        code: -1,
                        msg: "统计用户数量失败。",
                        error,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "获取用户总人数成功。",
                        total: among[0]["total"],
                    });
                }
            });
        });
    },
};
